from datetime import datetime

from api.search.mapping_region import mapping_region
from api.search.schema_alumni import Member
from api.search.utils import activity_import, role_import
from config import col_activity, col_register, col_alumni, col_institution
from task_utils.task_institution_overview import task_person_reputation
from task_utils.task_es import score_alumni_score
from core import strutil

activity_col = col_activity
register_col = col_register
inst_col = col_institution
alumni_col = col_alumni


def clean_region(region):
    if not region:
        return "", "", ""

    if region:
        province = region.get("province")
        city = region.get("city")
        district = region.get("district")
        return province, city, district


def region_map(region):
    if not region:
        return ""
    province = region
    if not province:
        return ""
    for k, v in mapping_region.items():
        checker = [item for item in v if province.strip() in item]
        if checker:
            return k


def clean_media(media):
    data = []
    if not media:
        return []
    for med in media:
        data.append(med.get("path"))
    return []


def clean_dept(dept):
    if not isinstance(dept, list):
        dept = [dept]
    institutions = inst_col.find({"_id": {"$in": dept}}, {"institution_name": 1})
    data = []
    for inst in institutions:
        _kx = inst.get("level", -1)
        is_kx = True if _kx >= 0 else False
        data.append({"id": str(inst["_id"]), "institution_name": inst['institution_name'], "is_kexie": is_kx})
    return data


def get_name_en(alumni):
    name = alumni.get('name', alumni.get('name_zh'))
    if not name:
        return None
    if strutil.contain_zh(name):
        name = strutil.cn_name2en_name(name)
    return name


def clean_subject(subject):
    if not subject:
        return []
    subjects = [s for s in subject if s != '[]' and s != 'none']
    return subjects


def import_alumni(skip=None, size=None):
    """先算法人的分，在排序"""
    try:
        cursor = alumni_col.find({"is_deleted": {"$ne": True}}).skip(skip).limit(size)
        for alumni in cursor:

            register = register_col.find({"person_id": alumni["_id"], "is_attended": True},
                                         {"activity_id": 1, "level_of_role": 1}).batch_size(2)
            # 计算总分
            register = list(register)
            if register:
                _score = []
                for reg in register:
                    print(reg["activity_id"])
                    act = activity_col.find_one({"_id": reg["activity_id"], "is_deleted": {"$ne": True}})
                    score_act = act.get("importance_of_activities", "常规")
                    score_role = reg.get("level_of_role", "一般参与")
                    active_score = activity_import.get(score_act, 1) * role_import.get(score_role, 1)
                    _score.append(active_score)

                _sum_score = sum(_score)
                alumni_rate, alumni_ranking = score_alumni_score(str(alumni["_id"]))
                print(_sum_score, alumni_rate, alumni_ranking)
                mem = Member(
                    _id=str(alumni["_id"]),
                    id=str(alumni["_id"]),
                    person_id=str(alumni["_id"]),
                    number_of_applicants=len(register),  # number_of_applicants
                    name=alumni.get("name"),
                    self_label=alumni.get("self_label"),
                    nation=alumni.get("nation"),
                    name_zh=alumni.get("name_zh"),
                    identify_type=alumni.get("identify_type", "身份证"),
                    gender=alumni.get("gender"),
                    age=alumni.get("age"),
                    professional_titles=alumni.get("professional_titles"),
                    job_title=alumni.get("job_title"),
                    research_interests=alumni.get("academic_area"),
                    job_province=alumni.get("job_province"),
                    job_city=alumni.get("job_city"),
                    subject=clean_subject(alumni.get("subject", [])),
                    email=alumni.get("email", []),
                    cur_institution_name=alumni.get("cur_institution_name"),
                    cur_institution_department=alumni.get("cur_institution_department"),
                    identify_photo=alumni.get("identify_photo"),
                    degree=alumni.get("academic_qualification"),
                    graduate_school=alumni.get("graduate_school"),
                    academic_qualification=alumni.get("academic_qualification"),
                    political_status=alumni.get("political_status"),
                    region=region_map(alumni.get("job_province")),
                    alumni_score=task_person_reputation(alumni.get("_id")),  # fixme 计算身份价值 alumni_score
                    create_at=datetime.utcnow(),
                    update_at=datetime.utcnow(),
                    prank_alumni_score=alumni_rate,
                    rank_alumni_score=alumni_ranking,
                    active=_sum_score,
                    activation=_sum_score,
                    belongs_inst=alumni.get("belongs_inst", [-1])

                )
                name = alumni.get('name', alumni.get('name_zh'))
                if strutil.contain_zh(name):
                    mem.name_pinyin = strutil.cn_name2pinyin(name)
                mem.save()

    except Exception as e:
        print(f"import_alumni error: {e}")

    finally:
        cursor.close()


if __name__ == '__main__':
    import_alumni(0, 20)
